package br.com.sendmail.operacoes;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletContext;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import br.com.sendmail.modelo.Template;
import br.com.sendmail.util.LoadDadosXML;

/**
 * 30/11/2012 - Templates.java 
 * Elton Souza - eltonds88@gmail.com
 * 
 * Classe que carrega os templates dos arquivos de configuracao.
 * O nome do arquivo deve ser send-mail.xml e deve se encontrar na pasta WEB-INF
 * 
 * Metodos privados ou pretected para garantir que somente a classe SendMail a utilize.
 *
 */
public final class Templates extends LoadDadosXML implements Serializable {

	private static final long serialVersionUID = 1L;

	private static List<Template> templates;

	protected Templates(ServletContext context) {
		if(templates == null) {
			carregarTemplates(context);
		}
	}

	private void carregarTemplates(ServletContext context) {
		try {
			Document doc = super.getArquivo(context.getRealPath(SendMail.ARQUIVO_CONF));
			if(doc != null) {
				templates = new ArrayList<Template>();
				NodeList nl = doc.getElementsByTagName(Template.XML_ELEMENT_NAME);
				if(nl != null && nl.getLength() > 0) {
					for(int i = 0 ; i < nl.getLength();i++) {
						//get email element
						Element template = (Element)nl.item(i);
						//add email to list
						templates.add(this.getTemplate(template));
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private Template getTemplate(Element template) throws Exception {
		return new Template(super.getValue(template, 0, "nome"), super.getValue(template, 0, "path"), 
				super.getValue(template, 0, "tipo"), super.getValue(template, 0, "assuntoEmail"), super.getValue(template, 0, "pathImagens")); 
	}

	protected static synchronized Template getTemplate(String nomeTemplate) {
		Template temp = null;
		if(templates != null) {
			for(Template t : templates) {
				if(t.getNome().equals(nomeTemplate)) {
					temp = t;
					break;
				}
			}
		}
		return temp;
	}
}
